package com.uni.api;

import com.uni.config.JWTProperties;
import com.uni.entity.Dto;
import com.uni.entity.ShopUser;
import com.uni.service.ShopUserService;
import com.uni.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthAPI {

    @Autowired
    private ShopUserService shopUserService;

    @Autowired
    private JWTProperties jwtProperties;

    /**
     * 用户登录
     * @param user 实例对象
     * @return 返回用户信息和token
     */
    @PostMapping("/login")
    public Dto doLogin(@RequestBody ShopUser user){

        ShopUser result = new ShopUser();
        // 验证用户明和密码
        if (ObjectUtils.isNotEmpty(user)) {
             result = shopUserService.login(user);
        }
        if (ObjectUtils.isEmpty(result)){
            return DtoUtil.returnFail("账号或密码错误", "401");
        }
        try {
            //生成token
            String token = JWTUtils.generateToken(
                    result, jwtProperties.getPrivateKey(), 30);

            result.setUserName(user.getUserName());
            JWTModel model = new JWTModel(result, token);
            return DtoUtil.returnSuccess("登录成功", model);
        } catch (Exception e) {
            log.error("生成token失败! ", e);
            return DtoUtil.returnFail("登录失败", "500");
        }
    }

    /**
     * 用户注册
     * @param user
     * @return 响应
     */
    @PostMapping("/reg")
    public Dto register(@RequestBody ShopUser user){
        ShopUser result = null;

        try {
            if (ObjectUtils.isNotEmpty(user)) {
                result = shopUserService.insert(user);
            }
        } catch (Exception e) {
            log.error("注册用户时异常: " , e);
            return DtoUtil.returnFail("注册失败", "500");
        }

        return DtoUtil.returnSuccess("注册成功" , result);
    }

    @PostMapping("/checkName")
    public Dto checkName(@RequestParam("userName") String userName){
        ShopUser user = shopUserService.getByName(userName);
        if (ObjectUtils.isNotEmpty(user))
            return DtoUtil.returnFail("用户名已存在", "405");

        return DtoUtil.returnSuccess("OK");
    }

}
